package com.jmpt.fangbohui.ui.personalcenter;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.NumberPicker;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.google.gson.Gson;
import com.jmpt.fangbohui.Constants;
import com.jmpt.fangbohui.R;
import com.jmpt.fangbohui.bean.BrokerInfoBean;
import com.jmpt.fangbohui.bean.EntryingHouseDropDownBean;
import com.jmpt.fangbohui.bean.EntryingHouseDropDownBean.Retval;
import com.jmpt.fangbohui.bean.LoginBean;
import com.jmpt.fangbohui.bean.UserEditIconBean;
import com.jmpt.fangbohui.bean.UserEditInfoBean;
import com.jmpt.fangbohui.bean.EntryingHouseDropDownBean.Retval.date_city;
import com.jmpt.fangbohui.bean.EntryingHouseDropDownBean.Retval.date_province;
import com.jmpt.fangbohui.dao.LoginSQLiteOperator;
import com.jmpt.fangbohui.ui.base.BaseHeadActivity;
import com.jmpt.fangbohui.utils.CompressPhotoUtils;
import com.jmpt.fangbohui.utils.DebugLog;
import com.jmpt.fangbohui.utils.ImageLoaderHelper;
import com.jmpt.fangbohui.utils.ToastHelper;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.lidroid.xutils.view.annotation.ViewInject;

public class EditUserInfoActivity extends BaseHeadActivity implements
		OnClickListener {
	public static final String FILENAME = "fbhNewIcon.jpg";
	private String email;

	private String birth_y;

	private String birth_m;

	private String qq;

	private String sex;

	private String zoneid;

	private String cityid;
	private String gender;

	private String provinceid;

	private String serv_zone;

	private String oldpic;

	private String picUrl;

	@ViewInject(R.id.iv_user_info_edit_icon_real)
	private ImageView iv_user_info_edit_icon_real;

	@ViewInject(R.id.et_user_info_edit_nicheng_real)
	private EditText et_user_info_edit_nicheng_real;

	@ViewInject(R.id.sp_user_info_edit_sex_real)
	private Spinner sp_user_info_edit_sex_real;

	@ViewInject(R.id.sp_user_info_edit_province_real)
	private Spinner sp_user_info_edit_province_real;
	
	@ViewInject(R.id.sp_user_info_edit_place_real)
	private Spinner sp_user_info_edit_place_real;

	@ViewInject(R.id.et_user_info_edit_email_real)
	private EditText et_user_info_edit_email_real;

	@ViewInject(R.id.tv_user_info_edit_birthday_real)
	private TextView tv_user_info_edit_birthday_real;

	@ViewInject(R.id.rl_user_info_icon)
	private RelativeLayout rl_user_info_icon;

	public final static int SUCCESS = 200;
	public final static int FAILED = 202;

	public final static int ICON_SUCCESS = 203;
	public final static int ICON_FAILED = 204;

	private static int RESULT_LOAD_IMAGE = 1;
	
	private List<String> sexList ;

	public File newPic;
	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			hideLoading();
			switch (msg.what) {
			case SUCCESS:

				finish();
				break;
			case FAILED:

				ToastHelper.ShowToast("网络异常，请稍后再试", EditUserInfoActivity.this);

				break;
			case ICON_SUCCESS:

				break;
			case ICON_FAILED:

				break;

			}

		};
	};

	private String picturePath;

	private Bitmap compressBitmap;
	private LoginSQLiteOperator oper;
	private SharedPreferences sp;
	private EntryingHouseDropDownBean dropDownBean;
	private ArrayList<String> province;
	private ArrayList<String> city;
	private ArrayList<String> provinceIds;
	private ArrayList<String> cityIds;
	private Retval result;
	private ArrayAdapter<String> provinceAdapter;
	private ArrayAdapter<String> cityAdapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_edit_user_info);
		ViewUtils.inject(this);
		initSpinnerData();
		
	}
	private void initSpinnerData() {
		showLoading();
		sp = getSharedPreferences("config", MODE_PRIVATE);
		String cacheDropDown = sp.getString(
				Constants.SharedPreferences.CACHEDROPDOWN, null);
		if (TextUtils.isEmpty(cacheDropDown)) {
			parsersAddress(cacheDropDown);
		}
		HttpUtils http = new HttpUtils();
		http.send(HttpMethod.GET, Constants.URL.SecondaryHousingDropDown,
				new RequestCallBack<String>() {

					@Override
					public void onFailure(HttpException arg0, String arg1) {
						hideLoading();
					}

					@Override
					public void onSuccess(ResponseInfo<String> arg0) {
						sp.edit()
								.putString(
										Constants.SharedPreferences.CACHEDROPDOWN,
										arg0.result).commit();
						parsersAddress(arg0.result);
					}
				});
	}

	protected void parsersAddress(String result) {
		hideLoading();
		DebugLog.i(result);
		Gson gson = new Gson();
		dropDownBean = gson.fromJson(result, EntryingHouseDropDownBean.class);
		// 拆分数据
		if (dropDownBean != null) {
			splitList(dropDownBean);
		}
	}
	private void splitList(EntryingHouseDropDownBean bean) {
		province = new ArrayList<String>();
		city = new ArrayList<String>();

		provinceIds = new ArrayList<String>();
		cityIds = new ArrayList<String>();

		result = bean.retval;
		for (date_province date_provinces : result.date_province) {
			province.add(date_provinces.ProvinceName);
			provinceIds.add(date_provinces.ProvinceID);
		}
		for (date_city date_citys : result.date_city) {
			city.add(date_citys.CityName);
			cityIds.add(date_citys.CityID);
		}
		getExtra();
		initView();
	}
	private void initView() {
		showTitle("修改信息");
		showBackButton(new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		});
		rl_user_info_icon.setOnClickListener(this);
		
		
		
	}

	private void getExtra() {
		Intent intent = getIntent();
		email = intent.getStringExtra("email");
		birth_y = intent.getStringExtra("birth_y");
		birth_m = intent.getStringExtra("birth_m");
		qq = intent.getStringExtra("qq");
		sex = intent.getStringExtra("sex");
		zoneid = intent.getStringExtra("zoneid");
		cityid = intent.getStringExtra("city");
		provinceid = intent.getStringExtra("provinceid");
		serv_zone = intent.getStringExtra("serv_zone");
		oldpic = intent.getStringExtra("oldpic");
		picUrl = intent.getStringExtra("picUrl");
		sexList = new ArrayList<String>();
		sexList.add("男");
		sexList.add("女");
		sp_user_info_edit_sex_real.setAdapter(new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_dropdown_item, sexList));
		sp_user_info_edit_sex_real.setOnItemSelectedListener(new OnItemSelectedListener() {


			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				gender = sexList.get(position);
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
				// TODO Auto-generated method stub
				
			}
		});
		int indexOf = sexList.indexOf(sex);
		sp_user_info_edit_sex_real.setSelection(indexOf);
		
		et_user_info_edit_email_real.setText(email);
		for(date_province element : result.date_province){
			if(provinceid.equals(element.ProvinceID)){
			}
		}
		sp_user_info_edit_province_real.setOnItemSelectedListener(new OnItemSelectedListener(){

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id)
			{
				cityFilter(position);
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent)
			{
				
			}});
		sp_user_info_edit_place_real.setOnItemSelectedListener(new OnItemSelectedListener()
		{

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id)
			{
				cityid = cityIds.get(position)		;		
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent)
			{
				
			}
		});
		provinceAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_dropdown_item, province);
		sp_user_info_edit_province_real.setAdapter(provinceAdapter);
		sp_user_info_edit_province_real.setSelection(provinceIds.indexOf(provinceid), true);
		tv_user_info_edit_birthday_real.setText(birth_y + "年" + birth_m + "月");

		ImageLoaderHelper.displayImage(picUrl, iv_user_info_edit_icon_real);
	}
	private void cityFilter(int position) {
		if(provinceIds == null|| provinceIds.size() == 0)
			return;
		provinceid = provinceIds.get(position);
		DebugLog.i(" 省份 select"+province.get(position));
		DebugLog.i(" 省份 select"+ provinceid);
		city.clear();
		cityIds.clear();
		for (date_city element : dropDownBean.retval.date_city) {
			if (element.ProvinceID.equals(provinceid)) {
				city.add(element.CityName);
				cityIds.add(element.CityID);
			}
		}
		if(cityAdapter == null){
			cityAdapter = new ArrayAdapter<String>(this,
					android.R.layout.simple_spinner_dropdown_item, city);
			sp_user_info_edit_place_real.setAdapter(cityAdapter);
		}else{
			cityAdapter.notifyDataSetChanged();
		}
		sp_user_info_edit_place_real.setSelection(0);
	}
	public void editBirthday(View view) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		View inflate = View.inflate(this, R.layout.dialog_birthday, null);
		final NumberPicker np_dialog_birthday_year = (NumberPicker) inflate
				.findViewById(R.id.np_dialog_birthday_year);
		np_dialog_birthday_year.setMinValue(1950);
		np_dialog_birthday_year.setMaxValue(2015);
		np_dialog_birthday_year.setValue(2000);
		final NumberPicker np_dialog_birthday_month = (NumberPicker) inflate
				.findViewById(R.id.np_dialog_birthday_month);
		np_dialog_birthday_month.setMinValue(1);
		np_dialog_birthday_month.setMaxValue(12);
		builder.setView(inflate);
		builder.setNegativeButton("取消", null);
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				birth_y = np_dialog_birthday_year.getValue() + "";
				birth_m = np_dialog_birthday_month.getValue() + "";
				tv_user_info_edit_birthday_real.setText(birth_y + "年" + birth_m
						+ "月");
			}
		});
		builder.show();
	}

	public void config(View view) {
		showLoading();
		oper = new LoginSQLiteOperator(this);
		final List<String> querySessionId = oper.queryUserSessionId2();
		if (querySessionId.size() != 2) {
			return;
		}
		HttpUtils utils = new HttpUtils();
		RequestParams params = new RequestParams();
		params.addBodyParameter("UserId", querySessionId.get(0));
		params.addBodyParameter("em", et_user_info_edit_email_real.getText().toString().trim());
		params.addBodyParameter("gender", gender);
		params.addBodyParameter("city", cityid);
		params.addBodyParameter("provinceid", provinceid);
		params.addBodyParameter("birth_y", birth_y);
		params.addBodyParameter("birth_m", birth_m);
		DebugLog.i(querySessionId.get(0));
		DebugLog.i(et_user_info_edit_email_real.getText().toString().trim());
		DebugLog.i(birth_y);
		DebugLog.i(birth_m);

		utils.send(HttpMethod.POST, Constants.URL.CHANGEUSERINFO, params,
				new RequestCallBack<String>() {

					@Override
					public void onFailure(HttpException arg0, String arg1) {
						hideLoading();
						Message obtain = Message.obtain();
						obtain.what = FAILED;
						handler.sendMessage(obtain);
						DebugLog.i(arg1);
					}

					@Override
					public void onSuccess(ResponseInfo<String> arg0) {
						parser(arg0.result);
					}
				});
	}

	protected void parser(String result) {
		DebugLog.i(result);
		Gson gson = new Gson();
		UserEditInfoBean bean = gson.fromJson(result, UserEditInfoBean.class);
		ToastHelper.ShowToast(bean.msg, EditUserInfoActivity.this);
		hideLoading();
	}
	

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK
				&& null != data) {
			Uri selectedImage = data.getData();
			String[] filePathColumn = { MediaStore.Images.Media.DATA };

			Cursor cursor = getContentResolver().query(selectedImage,
					filePathColumn, null, null, null);
			cursor.moveToFirst();

			int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
			picturePath = cursor.getString(columnIndex);
			DebugLog.i(picturePath);
			cursor.close();

			compressBitmap = CompressPhotoUtils.compressImage(BitmapFactory
					.decodeFile(picturePath));
			CompressPhotoUtils.saveBitmap(compressBitmap);
			iv_user_info_edit_icon_real.setImageBitmap(compressBitmap);

			uploadIcon(picturePath);
		}
	}

	private void uploadIcon(String picturePath) {
		showLoading();
		HttpUtils utils = new HttpUtils();
		RequestParams params = new RequestParams();
		oper = new LoginSQLiteOperator(this);
		LoginBean query = oper.query();
		params.addBodyParameter("UserId", query.retval.getUserId());
		DebugLog.i(query.retval.getUserId());
		if(TextUtils.isEmpty(oldpic)){
			params.addBodyParameter("oldpic", "");
		}else{
			params.addBodyParameter("oldpic", oldpic);
		}
		File newIcon = new File(picturePath);
		DebugLog.i(newIcon.length() + "=length");
		DebugLog.i(oldpic + "oldpic");
		params.addBodyParameter("pic", newIcon);
		utils.send(HttpMethod.POST, Constants.URL.USER_UPLOAD_ICON,params,
				new RequestCallBack<String>() {

					@Override
					public void onFailure(HttpException arg0, String arg1) {
						Message obtain = Message.obtain();
						obtain.what = FAILED;
						handler.sendMessage(obtain);
						DebugLog.i(arg1);
						hideLoading();
					}

					@Override
					public void onSuccess(ResponseInfo<String> arg0) {
						parserIcon(arg0.result);
					}
				});
	}

	protected void parserIcon(String result) {
		hideLoading();
		DebugLog.i("parserIcon"+result);
		Gson gson = new Gson();
		UserEditIconBean bean = gson.fromJson(result, UserEditIconBean.class);
		if(Boolean.valueOf(bean.done)){
			ToastHelper.ShowToast("上传头像成功", this);
		}else{
			ToastHelper.ShowToast("上传头像失败", this);
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.rl_user_info_icon:
			Intent i = new Intent(
					Intent.ACTION_PICK,
					android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

			startActivityForResult(i, RESULT_LOAD_IMAGE);
			break;
		}
	}

}
